package com.jack.reactor;

import reactor.core.publisher.Flux;

import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Random;


/**
 * 测试Reactor库中的Flux使用
 * Created by zhang_j on 2019/10/23
 */
public class FluxTest {
    public static void main(String[] args) {
        fluxStaticTest();
        fluxGenerateTest();
        fluxCreateTest();
    }

    public static void fluxCreateTest(){
        Flux.create(sink->{
            for(int i=0;i<10;i++){
                sink.next(i);
            }
        }).subscribe(System.out::println);
    }

    public static void fluxGenerateTest(){
        Flux.generate(sink->{
           sink.next("Hello");
           sink.complete();
        }).subscribe(System.out::println);

        final Random random = new Random();
        Flux.generate(ArrayList::new,(list,sink)->{
            int value = random.nextInt(100);
            list.add(value);
            sink.next(value);
            if(list.size() == 10){
                sink.complete();
            }
            return list;
        }).subscribe(System.out::println);
    }

    public static void fluxStaticTest(){
        Flux.just("Hello", "World").subscribe(System.out::println);
        Flux.fromArray(new Integer[] {1, 2, 3}).subscribe(System.out::println);
        Flux.empty().subscribe(System.out::println);
        Flux.range(1, 10).subscribe(System.out::println);
        Flux.interval(Duration.of(10, ChronoUnit.SECONDS)).subscribe(System.out::println);
        Flux.interval(Duration.of(1000, ChronoUnit.MILLIS)).subscribe(System.out::println);
    }
}
